<!--
 * @author dumeng
 学习统计
 -->
<template>
  <div class="course-statistics">
    <el-collapse-transition>
      <div class="course-search separate">
        <div class="course-search-inner">
          <el-row>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">部门</div>
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-cascader
                      ref="org"
                      v-model="searchQuery.orgId"
                      style="width:100%"
                      collapse-tags
                      clearable
                      :props="orgProps"
                    />
                  </el-col>
                  <el-col :span="6" style="line-height: 35px;">
                    <el-checkbox v-model="searchQuery.all">部门所有人员</el-checkbox>
                  </el-col>
                  <el-col :span="6" style="line-height: 35px;">
                    <el-checkbox v-model="searchQuery.cndDeptSubFlag">包含下级部门</el-checkbox>
                  </el-col>
                </el-row>
              </div>
            </el-col>
            <template v-if="!searchQuery.all">
              <el-col :span="6">
                <div class="search-inner-item">
                  <div class="item-label">姓名</div>
                  <el-input
                    v-model.trim="searchQuery.cndUserRealName"
                    style="width: 80%;"
                    class="filter-item"
                    placeholder="请输入用户名搜索"
                  />
                </div>
              </el-col>
              <el-col :span="6">
                <div class="search-inner-item">
                  <div class="item-label">手机号</div>
                  <el-input
                    v-model.trim="searchQuery.cndUserphoneNumber"
                    style="width: 80%;"
                    class="filter-item"
                    placeholder="请输入用户名搜索"
                  />
                </div>
              </el-col>
            </template>
          </el-row>
          <el-row>
            <el-col :span="8">
              <div class="search-inner-item">
                <div class="item-label">课程</div>
                <el-select
                  v-model="searchQuery.subjectId"
                  multiple
                  collapse-tags
                  filterable
                  placeholder="请选择课程"
                  style="width: 80%;"
                >
                  <el-option v-for="item in courses" :key="item.id" :label="item.courseName" :value="item.id" />
                </el-select>
              </div>
            </el-col>
            <el-col :span="16">
              <div class="search-inner-item" style="width: 95%;">
                <div class="item-label">学习时间</div>
                <el-date-picker
                  v-model.trim="searchQuery.startTime"
                  style="width:45%;"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="开始时间"
                />
                <span style="padding: 0 10px;">至</span>
                <el-date-picker
                  v-model.trim="searchQuery.endTime"
                  style="width:45%;"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="结束时间"
                />
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="course-search-btn">
          <el-button type="primary" @click="handleStart">开启统计任务</el-button>
          <el-button class="filter-item" type="primary" @click="handleReset">重置</el-button>
        </div>
      </div>
    </el-collapse-transition>
    <div class="btn-container">
      <div class="btn-container-title">
        <span>学习统计</span>
      </div>
    </div>
    <div class="classify-tab">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane v-for="(item, n) in statusOptions" :key="n" :label="item.name" :name="item.value" />
      </el-tabs>
    </div>
    <div class="table">
      <my-table
        :list="list"
        :filter-column="filtercolumn"
        tag="courseStatistics"
        operationwidth="80"
        :list-loading="listLoading"
      >
        <el-table-column label="操作" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleRefresh(scope.row)">刷新</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="text" size="mini" @click="handleExport(scope.row)">导出</el-button>
            <el-button type="text" size="mini" @click="handleAgain(scope.row)">重新统计</el-button>
            <el-button type="text" size="mini" @click="handleView(scope.row)">查看明细</el-button>
          </template>
        </el-table-column>
      </my-table>
    </div>
    <div class="btn-pagion fix">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.pageSize"
        @pagination="getList"
      />
    </div>
    <el-drawer title="统计详情" :visible.sync="drawer" direction="ttb" size="100%" destroy-on-close>
      <statistics-result :id="id" :obj="obj" />
    </el-drawer>
  </div>
</template>

<script>
import {
  querySubject,
  queryPage,
  insert,
  again,
  exportMask,
  exportNoMask,
  del,
  getComAndOrgTree
} from '@/views/skill/course/api/statistics'
import Pagination from '@/components/Pagination'
import MyTable from '@/components/Table'
import permission from '@/directive/permission/index.js' // 权限判断指令
import StatisticsResult from '../components/statisticsResult'
import { exportSign } from '@/utils/fileImportOrExportSign'
import { exportCheck } from '@/utils/sensitiveInfoExportCheck'

export default {
  name: 'CourseStatistics',
  components: { Pagination, MyTable, StatisticsResult },
  directives: { permission },
  data() {
    return {
      fullscreenLoading: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      searchQuery: {
        startTime: '',
        endTime: '',
        cndUserRealName: '',
        cndUserphoneNumber: '',
        all: false,
        cndDeptSubFlag: false,
        orgId: [],
        subjectId: []
      },
      activeTab: 'LEARN_VIDEO',
      statusOptions: [
        {
          value: 'LEARN_VIDEO',
          name: '视频课程'
        },
        {
          value: 'LEARN_AUDIO',
          name: '音频课程'
        }
      ],
      orgProps: {
        label: 'name',
        value: 'id',
        multiple: true,
        checkStrictly: true,
        lazy: true,
        lazyLoad(node, resolve) {
          let params = {}
          if (node.level !== 0) {
            if (node.data.deptId !== '') {
              params = {
                parentId: node.data.orgId,
                deptPId: node.data.deptId
              }
            } else {
              params = {
                parentId: node.data.id
              }
            }
          }
          getComAndOrgTree(params).then(res => {
            resolve(res.data.data)
          }).catch(() => {
            resolve([])
          })
        }
      },
      list: [],
      total: 0,
      listLoading: false,
      id: '',
      obj: {},
      drawer: false,
      courses: []
    }
  },
  computed: {},
  created() {
    this.getCourses()
    this.getList()
  },
  methods: {
    /**
     * 选项卡切换
     */
    handleTabClick(tab, event) {
      this.listQuery.page = 1
      this.courses = []
      this.getCourses()
      this.getList()
    },
    getCourses() {
      return new Promise((resolve, reject) => {
        querySubject({
          status: 'KCZT01',
          courseType: this.activeTab === 'LEARN_VIDEO' ? 'KCLX01' : 'KCLX03'
        }).then(res => {
          this.courses = res.data.data || []
        }).catch(error => {
          reject(error)
        })
      })
    },
    filtercolumn(scope, item) {
      if (item === 'taskRunningState') {
        return scope.row[item] === '0' ? '待执行' : scope.row[item] === '1' ? '执行中' : '已结束'
      } else {
        return scope.row[item]
      }
    },
    getList(obj) {
      this.listLoading = true
      var query = {
        taskType: this.activeTab,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit
      }
      return new Promise((resolve, reject) => {
        queryPage(query).then(response => {
          this.list = response.data.data.rows
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },

    handleStart() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      const params = {
        taskType: this.activeTab,
        cndUserRealName: this.searchQuery.cndUserRealName,
        cndUserphoneNumber: this.searchQuery.cndUserphoneNumber,
        cndDeptIds: this.searchQuery.orgId.length > 0 ? this.searchQuery.orgId.join(',') : '',
        cndDeptSubFlag: this.searchQuery.cndDeptSubFlag ? 1 : 0,
        cndDeptUserSubFlag: this.searchQuery.all ? 1 : 0,
        cndStartTime: this.searchQuery.startTime,
        cndEndTime: this.searchQuery.endTime,
        cndBreakthroughIds: this.searchQuery.subjectId.length > 0 ? this.searchQuery.subjectId.join(',') : ''
      }
      return new Promise((resolve, reject) => {
        insert(params).then(() => {
          loading.close()
          this.$message({
            title: '成功',
            message: '统计任务开启成功',
            type: 'success',
            duration: 2000
          })
          this.handleReset()
          this.listQuery.page = 1
          this.getList()
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleReset() {
      this.searchQuery.cndUserRealName = ''
      this.searchQuery.cndUserphoneNumber = ''
      this.searchQuery.cndDeptSubFlag = false
      this.searchQuery.orgId = []
      this.searchQuery.all = false
      this.searchQuery.startTime = ''
      this.searchQuery.endTime = ''
      this.searchQuery.subjectId = []
    },
    handleExport(row) {
      const obj = exportSign({ taskId: row.id }).obj
      exportCheck('BREAK_THROUGH', row.id, exportMask, exportNoMask, obj, '学习统计.xlsx')
    },
    handleView(row) {
      const obj = {
        org: row.cndDeptIdsValue ? row.cndDeptIdsValue.split(',') : '',
        name: row.cndUserRealName,
        phone: row.cndUserphoneNumber,
        all: row.all,
        down: row.cndDeptSubFlag,
        startTime: row.cndStartTime,
        endTime: row.cndEndTime,
        subject: row.cndBreakthroughIdsValue ? row.cndBreakthroughIdsValue.split(',') : ''
      }
      this.obj = Object.assign({}, obj)
      this.id = row.id
      this.drawer = true
    },

    handleAgain(row) {
      this.$confirm('确定要重新统计吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          again(row.id).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '重新统计成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => {
      })
    },

    handleDelete(row) {
      this.$confirm('确定删除该统计任务吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          del(row.id).then(() => {
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            reject(error)
          })
        })
      }).catch(() => {
      })
    },
    handleRefresh() {
      this.getList()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
$mainColor: #18a5fd;
@import '@/styles/mixin.scss';
.course-statistics {
  padding: 10px;

  .el-input__prefix {
    display: none;
  }

  .el-date-editor .el-range-separator {
    padding: 0;
  }

  .course-search {
    background-color: #fff;
    padding: 0 10px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;

      &_login {
        font-size: 20px;
      }
    }

    .search-input {
      width: 60%;
      position: relative;

      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;
      line-height: 36px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      line-height: 36px;
    }

    .course-search-btn {
      display: inline-block;
      float: right;

      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }

      .course-search-more {
        font-size: 14px;
        font-weight: 500;
        color: $mainColor;
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .course-search-inner {
        padding-top: 10px;

        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }

          .el-input {
            position: relative;

            .el-input__inner {
              border: none;
              padding: 0;
            }

            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }

      .course-search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .btn-container {
    display: flex;
    align-items: center;
    margin-top: 5px;
    margin-bottom: 5px;

    .btn-container-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .el-checkbox__label {
    font-weight: 400;
  }

  /*.roletree{*/
  /*  .el-form-item__label{*/
  /*    position: relative;*/
  /*    &:before{*/
  /*      content: '*';*/
  /*      color: red;*/
  /*      position: absolute;*/
  /*      left: 1px;*/
  /*      top: 3px;*/
  /*    }*/
  /*  }*/
  /*}*/
  .el-form-item__label {
    width: 90px !important;
  }

  .el-form-item__content {
    margin-left: 90px !important;
  }
}
</style>
